import type { Context } from 'koa'
import {
  inseretCarpoolType,
  updateCarpoolType,
  deleteCarpoolType,
  selectCarpoolType,
} from '../service/carpooltype.service.ts'
import {
  CarpoolTypeCreateError,
  CarpoolTypeUpdateError,
  CarpoolTypeDeleteError,
  CarpoolTypeSelectError,
} from '../constant/err.type.ts'

class CarpoolTypeController {
  // 查询拼车类型
  async getCarpoolType(ctx: Context) {
    try {
      const carpoolTypes = ctx.request.query.carpoolTypes as string
      const ids = carpoolTypes.split(',')
      const data = await selectCarpoolType(ids)
      ctx.echo({ data })
    } catch (error) {
      CarpoolTypeSelectError.error = ctx.seqErr(error)
      return ctx.app.emit('error', CarpoolTypeSelectError, ctx)
    }
  }

  // 新增拼车类型
  async addCarpoolType(ctx: Context) {
    try {
      const { carpoolType, carpoolTypeName, remark } = ctx.request.body
      await inseretCarpoolType({
        carpoolType,
        carpoolTypeName,
        remark,
      })
      ctx.echo({ msg: '新增成功' })
    } catch (error) {
      CarpoolTypeCreateError.error = ctx.seqErr(error)
      return ctx.app.emit('error', CarpoolTypeCreateError, ctx)
    }
  }

  // 更新拼车类型
  async editCarpoolType(ctx: Context) {
    try {
      const { carpoolTypeId, carpoolType, carpoolTypeName, remark } =
        ctx.request.body
      await updateCarpoolType({
        carpoolTypeId,
        carpoolType,
        carpoolTypeName,
        remark,
      })
      ctx.echo({ msg: '更新成功' })
    } catch (error) {
      CarpoolTypeUpdateError.error = ctx.seqErr(error)
      return ctx.app.emit('error', CarpoolTypeUpdateError, ctx)
    }
  }

  // 删除拼车类型
  async removeCarpoolType(ctx: Context) {
    try {
      const { carpoolTypeId } = ctx.params
      await deleteCarpoolType({ carpoolTypeId })
      ctx.echo({ msg: '删除成功' })
    } catch (error) {
      CarpoolTypeDeleteError.error = ctx.seqErr(error)
      return ctx.app.emit('error', CarpoolTypeDeleteError, ctx)
    }
  }
}

const carpoolTypeController = new CarpoolTypeController()
export const {
  getCarpoolType,
  addCarpoolType,
  editCarpoolType,
  removeCarpoolType,
} = carpoolTypeController
export default carpoolTypeController
